package solutions.leetcode.normal

import java.util.*

/**
 * @author lizhidong
 * <a href="https://leetcode.cn/problems/design-authentication-manager/">1797. 设计一个验证系统</a>
 */
private class Solution1797 {
    class AuthenticationManager(val timeToLive: Int) {
        val queue = LinkedList<Pair<String, Int>>()

        fun generate(tokenId: String, currentTime: Int) {
            checkTime(currentTime)
            queue.removeIf { it.first == tokenId }
            queue.offer(Pair(tokenId, currentTime))
        }

        fun renew(tokenId: String, currentTime: Int) {
            checkTime(currentTime)
            if (queue.removeIf { it.first == tokenId }) {
                queue.offer(Pair(tokenId, currentTime))
            }
        }

        fun countUnexpiredTokens(currentTime: Int): Int {
            checkTime(currentTime)
            return queue.size
        }

        private fun checkTime(currentTime: Int) {
            while (queue.isNotEmpty()) {
                val first = queue.peek()
                if (first.second <= currentTime - timeToLive) {
                    queue.poll()
                } else {
                    break
                }
            }
        }
    }
}

fun main() {
    val auth = Solution1797.AuthenticationManager(5)
    auth.renew("aaa", 1)
    auth.generate("aaa", 2)
    println(auth.countUnexpiredTokens(6))
    auth.generate("bbb", 7)
    auth.renew("aaa", 8)
    auth.renew("bbb", 10)
    println(auth.countUnexpiredTokens(15))
}